package com.future.mayi.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.future.mayi.model.UserInfoModel;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class SharedPreferencesUtils {


    //sp枚举类  fileName存储的文件名   objectName存储的对象名
    public enum SpEnum {


        //客服电话
        servicePhone("config", "service_phone"),
        ShareGoods("config", "share_goods"),
        City("config", "city"),
        Kefu("config", "Kefu"),
        //用户信息
        UserVo("user", "user_vo"),
        //用户信息——登录的ID
        LoginId("user", "user_info_id"),
        //用户信息——登录的用户名
        LoginNickName("user", "nick_name"),
        LoginUserLevel("user", "user_level"),
        //用户信息——登录的头像
        LoginHeadImg("user", "head_img"),
        //用户信息——手机号
        LoginPhone("user", "phone"),
        LoginPhoneCountryId("user", "country_id"),
        LoginPhoneCountryCode("user", "country_code"),
        //用户信息——生日
        LoginBirthday("user", "birthday"),
        LoginSex("user", "sex"),
        LoginStatus("user", "status"),
        LoginIdentity("user", "identity"),
        LoginRefusalReason("user", "refusal_reason"),
        LoginRefusalTime("user", "refusal_time"),
        //用户信息——登录的token
        LoginToken("user", "token"),

        LoginRcToken("user", "rc_token"),
        //钱包余额
        WalletBalance("user", "wallet_balance"),
        Referee("user", "referee"),
        InviteCode("user", "invite_code"),
        WalletFrozen("user", "wallet_frozen"),
        //可用红包数量
        RedpackNum("user", "redpack_num"),
        //可用优惠券数量
        CouponNum("user", "coupon_num"),

        NewGoodsOrderHint("user", "new_goods_order_hint"),

        //系统消息
        SystemMsgCount("user", "system_msg_count"),

        UserSearchCache("user", "user_search_cache"),

        UserAddress("user", "user_address"),

        UserSetPayPassword("user", "user_set_pay_password"),

        WxPayResp("user", "wx_pay_resp"),
        IsShowMyParent("user", "is_show_my_parent"),


        //是否设置推送的别名
        hasSetAlias("user", "has_set_alias");


        private String fileName;
        private String objectName;

        SpEnum(String fileName, String objectName) {
            this.fileName = fileName;
            this.objectName = objectName;
        }

        public String getObjectName() {
            return objectName;
        }

        public String getFileName() {
            return fileName;
        }
    }


    public static boolean setUser(Context context, UserInfoModel userInfoModel) {
        if (userInfoModel == null) return false;
        if (context == null) return false;
        SharedPreferences sp = context.getSharedPreferences(SharedPreferencesUtils.SpEnum.LoginNickName.getFileName(), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(SharedPreferencesUtils.SpEnum.LoginSex.getObjectName(), userInfoModel.getGender());
        editor.putInt(SharedPreferencesUtils.SpEnum.LoginStatus.getObjectName(), userInfoModel.getStatus());
        editor.putInt(SharedPreferencesUtils.SpEnum.LoginIdentity.getObjectName(), userInfoModel.getIdentity());
        editor.putInt(SpEnum.LoginUserLevel.getObjectName(), userInfoModel.getLevel());

        editor.putString(SharedPreferencesUtils.SpEnum.LoginNickName.getObjectName(), userInfoModel.getNickname() == null ? "" : userInfoModel.getNickname());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginPhone.getObjectName(), userInfoModel.getMobile() == null ? "" : userInfoModel.getMobile());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginHeadImg.getObjectName(), userInfoModel.getAvatar() == null ? "" : userInfoModel.getAvatar());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginBirthday.getObjectName(), userInfoModel.getBirthday() == null ? "" : userInfoModel.getBirthday());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginRefusalReason.getObjectName(), userInfoModel.getRefusal_reason() == null ? "" : userInfoModel.getRefusal_reason());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginRefusalTime.getObjectName(), userInfoModel.getRefusal_time() == null ? "" : userInfoModel.getRefusal_time());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginPhoneCountryId.getObjectName(), userInfoModel.getCountry_id() == null ? "" : userInfoModel.getCountry_id());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginPhoneCountryCode.getObjectName(), userInfoModel.getCountry_code() == null ? "" : userInfoModel.getCountry_code());
        if (!TextUtils.isEmpty(userInfoModel.getToken()))
            editor.putString(SharedPreferencesUtils.SpEnum.LoginToken.getObjectName(), userInfoModel.getToken());
        editor.putString(SharedPreferencesUtils.SpEnum.LoginId.getObjectName(), String.valueOf(userInfoModel.getUser_id()));
        SharedPreferencesCompat.apply(editor);
        return true;
    }

    public static int set(Context context, SpEnum type, Object object) {
        if (context == null)
            return 0;
        if (object == null)
            object = "";
        put(context, type.getFileName(), type.getObjectName(), object);
        return 0;
    }


    public static Object get(Context context, SpEnum type, Object object) {
        if (context == null)
            return object;
        return read(context, type.getFileName(), type.getObjectName(), object);
    }


    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    private static Object read(Context context, String name, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }
        return null;
    }

    /**
     * 保存数据的方法
     * 试用保存单个字段
     *
     * @param context
     * @param key
     * @param object
     */
    private static void put(Context context, String name, String key, Object object) {
        SharedPreferences sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param context
     * @param type
     */
    private static void remove(Context context, SpEnum type) {
        SharedPreferences sp = context.getSharedPreferences(type.getFileName(), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(type.getObjectName());
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除某个文件的所有数据
     *
     * @param context
     * @param type
     */
    public static void clear(Context context, SpEnum type) {
        SharedPreferences sp = context.getSharedPreferences(type.getFileName(), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }


    /**
     * 查询文件里面否已经存在某个key
     *
     * @param context
     * @param type
     * @return
     */
    private static boolean contains(Context context, SpEnum type) {
        SharedPreferences sp = context.getSharedPreferences(type.getFileName(), Context.MODE_PRIVATE);
        return sp.contains(type.getObjectName());
    }

    /**
     * 返回所有的键值对
     *
     * @param context
     * @param type
     * @return
     */
    private static Map<String, ?> getAll(Context context, SpEnum type) {
        SharedPreferences sp = context.getSharedPreferences(type.getFileName(),
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }

}